from django.db import models
from django.conf import settings
import json


class Conversation(models.Model):
    """对话会话"""
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='用户')
    title = models.CharField(max_length=200, verbose_name='会话标题')
    knowledge_base = models.ForeignKey('knowledge.KnowledgeBase', null=True, blank=True,
                                       on_delete=models.SET_NULL, verbose_name='关联知识库')
    is_archived = models.BooleanField(default=False, verbose_name='是否归档')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'conversation'
        verbose_name = '对话会话'
        verbose_name_plural = verbose_name
        ordering = ['-updated_at']

    def __str__(self):
        return f'{self.user.username} - {self.title}'


class Message(models.Model):
    """对话消息"""
    ROLE_CHOICES = [
        ('user', '用户'),
        ('assistant', '助手'),
        ('system', '系统'),
    ]

    conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE,
                                     related_name='messages', verbose_name='对话会话')
    role = models.CharField(max_length=10, choices=ROLE_CHOICES, verbose_name='角色')
    content = models.TextField(verbose_name='消息内容')
    tokens = models.IntegerField(null=True, blank=True, verbose_name='Token数')
    model = models.CharField(max_length=50, null=True, blank=True, verbose_name='使用的模型')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'message'
        verbose_name = '对话消息'
        verbose_name_plural = verbose_name
        ordering = ['created_at']

    def __str__(self):
        return f'{self.role}: {self.content[:50]}'


class RetrievedDocument(models.Model):
    """检索到的文档"""
    message = models.ForeignKey(Message, on_delete=models.CASCADE,
                                related_name='retrieved_docs', verbose_name='关联消息')
    document = models.ForeignKey('knowledge.Document', on_delete=models.CASCADE, verbose_name='文档')
    chunk_index = models.IntegerField(null=True, blank=True, verbose_name='分块索引')
    relevance_score = models.FloatField(verbose_name='相关度分数')
    content = models.TextField(verbose_name='检索内容')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'retrieved_document'
        verbose_name = '检索文档'
        verbose_name_plural = verbose_name
        ordering = ['-relevance_score']

    def __str__(self):
        return f'{self.document.title} - Score: {self.relevance_score}'


class QuestionFeedback(models.Model):
    """问答反馈"""
    RATING_CHOICES = [
        (1, '很差'),
        (2, '差'),
        (3, '一般'),
        (4, '好'),
        (5, '很好'),
    ]

    message = models.OneToOneField(Message, on_delete=models.CASCADE,
                                   related_name='feedback', verbose_name='关联消息')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='用户')
    rating = models.IntegerField(choices=RATING_CHOICES, verbose_name='评分')
    comment = models.TextField(null=True, blank=True, verbose_name='评价内容')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'question_feedback'
        verbose_name = '问答反馈'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']

    def __str__(self):
        return f'{self.user.username} - {self.get_rating_display()}'
